package com.qfedu.fmmall.interceptor;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.qfedu.fmmall.common.status.ResStatus;
import com.qfedu.fmmall.common.vo.ResultVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;

/**
 * @author : yanBin
 * @date :2021/12/14 11:17
 */
@Component
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 前置拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        //浏览器发送请求时，第一次试探请求，请求方式 OPTIONS
        if ("OPTIONS".equals(method)){
            return true;
        }
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            doResponse(response,new ResultVO(ResStatus.NO.getCode(),"token字符串为空",null));
            return false;//token字符串为空"
        }
        //解析token
        try {
            //用redis来获取token数据
            String s = stringRedisTemplate.boundValueOps(token).get();
            if (StringUtils.isBlank(s)){
                doResponse(response,new ResultVO(ResStatus.NO.getCode(),"token字符串为空",null));
                return false;//token字符串为空"
            }
            stringRedisTemplate.boundValueOps(token).expire(30, TimeUnit.MINUTES);
            return true;

            /**
            //jwt解析token
            JwtParser parser = Jwts.parser();
            parser.setSigningKey("123456");
            //如果token正确（密码正确，在有效期内）则正常执行，否则则报错
            Jws<Claims> claimsJws = parser.parseClaimsJws(token);
            return true;
        } catch (ExpiredJwtException e) {
            doResponse(response,new ResultVO(ResStatus.NO.getCode(),"登录过期，请重新登录",null));
        }catch (UnsupportedJwtException e){
            doResponse(response,new ResultVO(ResStatus.NO.getCode(),"token不合法，请自重",null));
             */
        }catch(Exception e){
            doResponse(response,new ResultVO(ResStatus.NO.getCode(),"请登录",null));
        }
        return false;
    }

    /**
     * response向前端发送
     * @param response
     * @param resultVO
     * @throws IOException
     */
    private void doResponse(HttpServletResponse response, ResultVO resultVO) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String s = new ObjectMapper().writeValueAsString(resultVO);
        out.print(s);
        out.flush();
        out.close();
    }
}
